<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;



function xfyun($sentence)
{
    $api = "https://ltpapi.xfyun.cn/v1/cws";
    $XAppid = "fa7c462f";
    $Apikey = "177f1afdcc6e0cbc268f914b7f5b4f52";
    $XCurTime = time();

    $Param = array(
        "type" => "dependent",
    );


    $text = $sentence;
    $Post = array(
        'text' => $text,
    );

    $XParam = base64_encode(json_encode($Param));
    $XCheckSum = md5($Apikey . $XCurTime . $XParam);
    $headers = array();
    $headers[] = 'X-CurTime:' . $XCurTime;
    $headers[] = 'X-Param:' . $XParam;
    $headers[] = 'X-Appid:' . $XAppid;
    $headers[] = 'X-CheckSum:' . $XCheckSum;
    $headers[] = 'Content-Type:application/x-www-form-urlencoded; charset=utf-8';
    return http_request($api, $Post, $headers);
}

function http_request($url, $post_data, $headers)
{
    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => $headers,
            'content' => $postdata,
            'timeout' => 5
        )
    );
    $context = stream_context_create($options);
    return file_get_contents($url, false, $context);
}

class SplitWordsController extends Controller
{
    //
    public function getStopWords(): array
    {
        return preg_split('[\n]',file_get_contents(base_path('assets/baidu_stopwords.txt')));
    }

    public function index(Request $request){
        $stopwords=$this->getStopWords();
        $sentence=$request->sentence;
        $begin=-1;
        $phrases=[];
        while(true){
            $pos=strpos($sentence, '"', $begin+1);
            if ($pos===false){
                break;
            }
            if ($begin==-1){
                $begin=$pos;
            }else{
                array_push($phrases, substr($sentence, $begin+1, $pos-$begin-1));
                $sentence=substr($sentence, 0, $begin).' '.substr($sentence, $pos+1);
                $begin=-1;
            }
        }
        $result=json_decode(xfyun($sentence));
        if ($result->code=='0'){
            $result->data->word=array_merge(array_values(array_diff($result->data->word, $stopwords)), array_values($phrases));
        }else{
            return [
                'code'=>'0',
                'data'=>[
                    'word'=>array_merge(array_values(array_diff(preg_split('[ ]', $sentence), $stopwords)), array_values($phrases))
                ]
            ];
        }
        return $result;
    }
}
